package mo.org.cm309.shoppingcart.service;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import mo.org.cm309.shoppingcart.dao.ProductDAO;
import mo.org.cm309.shoppingcart.entity.Cart;
import mo.org.cm309.shoppingcart.entity.Product;
import mo.org.cm309.shoppingcart.entity.User;

public class ProductService {
	public void add(Product product){
		ProductDAO.getInstance().insert(product);
	}
	
	public Product getProductById(long productId){
		Product product = ProductDAO.getInstance().findById(productId);
		byte[] image 	= product.getImage(); 
		if (image != null && image.length > 0)
			product.setImageEncode(Base64.encode(image));
		else
			product.setImageEncode("");
		return product;
	}
	
	public void update(Product product){
		byte[] image = product.getImage();
		if (image != null && image.length != 0){
			ProductDAO.getInstance().update(product);
		}else{
			ProductDAO.getInstance().updateWithOutImage(product);
		}
	}
	
	public Product setStock(Product product, int number){
		product.setStock(product.getStock() + number);
		return product;
	}
	
	public Cart addToCart(Cart cart, long productId, int quantity){
		if (cart == null){
			cart = new Cart();
		}
		cart.addProductToCart(productId, quantity);
		return cart;
	}
}
